<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-06-09 16:24:13
 * @LastEditors: william
 * @LastEditTime: 2025-10-23 11:47:36
-->
<template>
  <nw-PageTitle :title="$t('system.deviceManage')" isBack />
  <nw-PageContainer>
    <scroll-view
      class="scroll-content"
      scroll-y
      :style="{
        'min-height': bindDeviceList.length ? 'initial' : 'calc(100%)'
      }"
    >
      <view class="lists">
        <view class="block-title">
          <view class="bt-left">本机管理设备</view>
          <!-- <view class="bt-right">
            <nw-Button text="设备绑定" @click="handleDeviceBind"></nw-Button>
          </view> -->
        </view>
        <view
          v-if="bindDeviceList.length"
          class="list"
          v-for="(row, i) in bindDeviceList"
          :key="i"
        >
          <view class="list-title-wrap">
            <view class="ltw-left">
              <view class="list-title">{{ row.name }}</view>
              <view class="btn-wrap">
                <view
                  :class="[
                    'btn',
                    {
                      offline: row.onlineStatus === deviceConnectStatus.Offline
                    }
                  ]"
                  @click="handleDeviceUnBind(row)"
                >
                  {{
                    g_options.getOptionText(
                      g_options.deviceConnectStatusOptions,
                      row.onlineStatus,
                      '--'
                    )
                  }}
                </view>
              </view>
            </view>
            <view class="btn-wrap">
              <view class="btn" @click="handleDeviceUnBind(row)">
                解绑炒菜机
              </view>
            </view>
          </view>
          <view class="list-content">
            <up-row>
              <up-col span="6">
                <view class="li readonly">
                  <view class="li-label">{{ $t('system.cookerSn') }}:</view>
                  <view class="li-value">{{ row.sn }}</view>
                </view>
              </up-col>
              <up-col span="6">
                <view class="li readonly">
                  <view class="li-label">IP:</view>
                  <view class="li-value">{{ row.ip }}</view>
                </view>
              </up-col>
            </up-row>
            <view class="li active">
              <view class="li-label">{{ $t('system.nickName') }}</view>
              <view class="li-right">
                <view class="li-value">
                  {{ row.nickName }}
                </view>
                <view class="btn-wrap">
                  <view class="btn" @click="handleUpdateNickName(row)">
                    {{ $t('system.modifyNickname') }}
                  </view>
                </view>
              </view>
            </view>
            <view class="li active">
              <view class="li-label">{{ $t('system.hoodSn') }}</view>
              <view class="li-right">
                <view class="li-value">{{ row.bindOil }}</view>
                <view class="btn-wrap">
                  <view class="btn" @click="handleBindCooking(row)">
                    {{ row.bindOil ? '解绑' : '绑定' }} 油烟机
                  </view>
                </view>
              </view>
            </view>
            <view class="li active">
              <view class="li-label">电子秤SN</view>
              <view class="li-right">
                <view class="li-value">{{ row.bindElectronic }}</view>
                <view class="btn-wrap">
                  <view class="btn" @click="handleBindElecScale(row)">
                    {{ row.bindElectronic ? '解绑' : '绑定' }} 电子秤
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <Emptylist v-if="!bindDeviceList.length" />
      <view class="btn-bottom-wrap">
        <nw-Button
          text="下载更新设备"
          @click="handleDownloadDevice"
        ></nw-Button>
        <nw-Button text="绑定炒菜机" @click="handleDeviceBind"></nw-Button>
      </view>
    </scroll-view>

    <up-toast ref="uToastRef" />
    <StirFryDeviceBind
      v-if="stirFryDeviceVisible"
      v-model="stirFryDeviceVisible"
      @add="handleAddDevice"
    />
    <UpdateNickName
      v-if="updateNickNameVisible"
      v-model="updateNickNameVisible"
      :deviceSn="deviceSn"
      @update="handleUpdateNickName"
    />
    <CookerHoodDeviceBind
      v-if="cookerHoodDeviceVisible"
      v-model="cookerHoodDeviceVisible"
      :deviceSn="deviceSn"
      @add="handleAddDevice"
    />
    <ElecScaleDeviceBind
      v-if="elecScaleDeviceVisible"
      v-model="elecScaleDeviceVisible"
      :deviceSn="deviceSn"
      @add="handleAddDevice"
    />
    <UnBindCooking
      v-if="unBindCookingVisible"
      v-model="unBindCookingVisible"
      :deviceSn="deviceSn"
      :sn="sn"
      @update="handleUpdateDevice"
    />
    <UnBindElecScale
      v-if="unBindElecScaleVisible"
      v-model="unBindElecScaleVisible"
      :deviceSn="deviceSn"
      :sn="sn"
      @update="handleUpdateDevice"
    />
    <UnBindStirFryDevice
      v-if="unBindStirFryVisible"
      v-model="unBindStirFryVisible"
      :deviceSn="deviceSn"
      :sn="sn"
      @update="handleUpdateDevice"
    />
    <UpdateDevice
      v-if="updateDeviceVisible"
      v-model="updateDeviceVisible"
      :deviceSn="deviceSn"
      :sn="sn"
      @update="handleUpdateDevice"
    />
  </nw-PageContainer>
</template>

<script setup>
import StirFryDeviceBind from './component/StirFryDeviceBind.vue'
import UpdateNickName from './component/UpdateNickName.vue'
import CookerHoodDeviceBind from './component/CookerHoodDeviceBind.vue'
import ElecScaleDeviceBind from './component/ElecScaleDeviceBind.vue'
import UnBindCooking from './component/UnBindCooking.vue'
import UnBindElecScale from './component/UnBindElecScale.vue'
import UnBindStirFryDevice from './component/UnBindStirFryDevice.vue'
import UpdateDevice from './component/UpdateDevice.vue'

const { allDeviceList, bindDeviceList } = storeToRefs(useDeviceStore())
const { userInfo } = storeToRefs(useUserStore())
const uToastRef = ref(null)
const deviceConnectStatus = g_i.device.DeviceConnectStatus
// 弹框参数
const stirFryDeviceVisible = ref(false)
const updateNickNameVisible = ref(false)
const deviceSn = ref('')
const sn = ref('')
const cookerHoodDeviceVisible = ref(false)
const elecScaleDeviceVisible = ref(false)
const unBindCookingVisible = ref(false)
const unBindElecScaleVisible = ref(false)
const unBindStirFryVisible = ref(false)
const updateDeviceVisible = ref(false)

onMounted(_ => {
  if (bindDeviceList.value.length === 0 && allDeviceList.value.length === 0) {
    // 只有绑定的设备为空的时候，才自动从云端下载数据
    getDataList()
  }
  // getDataList()
  // console.log('绑定的设备列表：', bindDeviceList.value)
})

function getDataList() {
  const appId = g_utils.getAppId()
  g_api.device
    .apiDownloadDeviceInfo({
      tenantId: userInfo.value.tenantId,
      appId
    })
    .then(({ code, data }) => {
      if (code === 200 && data) {
        allDeviceList.value = data
        // 从云端同步已绑定的设备
        const dataList = g_.cloneDeep(data).filter(item => {
          item.appId = appId
          return item.type === 1 && item.bind === 1
        })
        const deviceList = bindDeviceList.value.reduce((prev, curr) => {
          if (curr.status * 1 === g_i.device.DeviceStatus.Idle) {
            // 对于空闲设备，检查云端是否有匹配项
            const matchedItem = dataList.find(
              dataItem => dataItem.sn === curr.sn
            )
            matchedItem
              ? prev.push(g_i.apiDataFormat(matchedItem, g_i.device.deviceInfo))
              : ''
          } else {
            // 保留非空闲状态的设备
            prev.push(curr)
          }
          return prev
        }, [])
        const sns = new Set(deviceList.map(item => item.sn))
        // 筛选出云端中未在本地设备列表中出现的新设备
        const filterData = dataList.filter(item => {
          if (!sns.has(item.sn)) {
            Object.assign(item, g_i.apiDataFormat(item, g_i.device.deviceInfo))
            return true
          }
        })
        bindDeviceList.value = [...deviceList, ...filterData]
        console.log('清洗后的设备列表：', bindDeviceList.value)
      }
    })
}

const handleDeviceBind = _ => {
  stirFryDeviceVisible.value = true
}

const handleDeviceUnBind = row => {
  sn.value = row.sn
  unBindStirFryVisible.value = true
}

const handleUpdateNickName = row => {
  updateNickNameVisible.value = true
  deviceSn.value = row.sn
}

const handleBindCooking = row => {
  deviceSn.value = row.sn
  sn.value = row.bindOil
  if (row.bindOil) {
    unBindCookingVisible.value = true
  } else {
    cookerHoodDeviceVisible.value = true
  }
}

const handleBindElecScale = row => {
  deviceSn.value = row.sn
  sn.value = row.bindElectronic
  if (row.bindElectronic) {
    unBindElecScaleVisible.value = true
  } else {
    elecScaleDeviceVisible.value = true
  }
}

const handleDownloadDevice = _ => {
  updateDeviceVisible.value = true
}

const handleAddDevice = _ => {
  uToastRef.value.show({
    type: 'success',
    message: g_t('system.bindSuccess')
  })
}

const handleUpdateDevice = _ => {
  uToastRef.value.show({
    type: 'success',
    message: g_t('system.unbindSuccess')
  })
}
</script>

<style lang="scss" scoped>
.scroll-content {
  max-height: initial;
  padding: 28rpx 20rpx 93 * 2+20rpx;
  box-sizing: border-box;
  .block-title {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;
    font-weight: 400;
    color: var(--color-333);
    .bt-right :deep(.nw-button) {
      height: 44rpx;
      padding: 0 14rpx;
      border-radius: 22rpx;
      .u-button__text {
        font-size: 22rpx !important;
        font-weight: 400;
      }
      &:not(.u-button--disabled) .u-button__text {
        color: var(--color-fff);
      }
    }
  }
  :deep(.empry-wrap) {
    height: calc(100% - 110rpx);
  }
  .nw-button-wrap {
    &.nw-button-wrap {
      margin-left: 14rpx;
    }
    :deep(.nw-button) {
      height: 54rpx;
      margin: initial;
      padding: 0 28rpx;
      border-radius: 28rpx;
      box-sizing: border-box;
      .u-button__text {
        font-size: 22rpx !important;
        font-weight: 400;
      }
      &:not(.u-button--disabled) .u-button__text {
        color: var(--color-fff);
      }
    }
  }
}

.lists {
  .list {
    margin-top: 22rpx;
    padding: 0 22rpx;
    background-color: var(--bg-color);
    border-radius: 18rpx;
    box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(6, 29, 23, 0.03);
    .list-title-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .ltw-left {
        display: flex;
        align-items: center;
        .btn {
          &.offline {
            background-color: #fb6567;
            color: #fff;
          }
        }
      }
    }
    .list-title {
      line-height: 24rpx;
      padding: 18rpx 0 20rpx 0;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      font-weight: 600;
      color: var(--color-333);
    }
  }
}
.list-content {
  .li {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    font-size: 22rpx;
    font-weight: 400;
    border-top: 1rpx solid var(--border-color);
    line-height: 22rpx;
    .li-label {
      flex-shrink: 0;
    }
    .li-value {
      margin-left: 14rpx;
    }
    &.readonly {
      color: var(--color-999);
    }
    &.active {
      .li-label {
        width: 140rpx;
        color: var(--color-666);
      }
      .li-value {
        color: var(--color-333);
      }
    }
    .li-right {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.list-title-wrap .btn-wrap,
.li-right .btn-wrap {
  flex-shrink: 0;
  margin-left: 10rpx;
  .btn {
    line-height: 18rpx;
    padding: 8rpx 12rpx;
    font-size: 18rpx;
    color: var(--main-theme);
    background-color: var(--active-bg-color);
    border-radius: 10rpx;
  }
}

.btn-bottom-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10rpx 48rpx 40rpx;
  box-sizing: border-box;
  .nw-button-wrap {
    width: 100%;
    + .nw-button-wrap {
      margin-top: 24rpx;
    }
  }
  :deep(.nw-button) {
    height: 54rpx;
    border-radius: 28rpx;
    background-color: #fff !important;
    border-color: #33bd88;
    .u-button__text {
      // line-height: 24rpx;
      font-size: 24rpx !important;
      color: var(--main-theme) !important;
    }
  }
}

.list-title-wrap .btn-wrap,
.li-right .btn-wrap {
  flex-shrink: 0;
  margin-left: 10rpx;
  .btn {
    line-height: 18rpx;
    padding: 8rpx 12rpx;
    font-size: 18rpx;
    color: var(--main-theme);
    background-color: var(--active-bg-color);
    border-radius: 10rpx;
  }
}
</style>
